const dayjs = require("dayjs");
function validatePhoneNumber(phoneNumber) {
  var pattern = /^1[3456789]\d{9}$/;
  return pattern.test(phoneNumber);
}
exports.home = async (req, res) => {
  const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const { gender, user_name, phone, base_name, user_code } = req.body;
  if (!phone) {
    return res.send({
      code: 0,
      msg: "请输入手机号",
    });
  } else if (!validatePhoneNumber(phone)) {
    return res.send({
      code: 0,
      msg: "手机号错误",
    });
  }
  if (!user_name) {
    return res.send({
      code: 0,
      msg: "请输入用户名",
    });
  }
  if (!gender) {
    return res.send({
      code: 0,
      msg: "请输入性别",
    });
  }
  if (!base_name) {
    return res.send({
      code: 0,
      msg: "请选择base地",
    });
  }
  if (!user_code) {
    return res.send({
      code: 0,
      msg: "请输入工号",
    });
  }
  const addSql = `SELECT *  FROM sign WHERE phone = '${phone}' OR user_code = '${user_code}'`;
  const addRes = await global.query(addSql)
  if (addRes?.length >= 1) {
    const id = addRes[0].id
    const sql_0 = `UPDATE sign SET gender='${gender}', user_name='${user_name}',phone='${phone}',base_name='${base_name}',user_code='${user_code}',update_time='${create_time}' WHERE id = ${id}`;
    const myPersonResult = await global.query(sql_0);
    if (myPersonResult.affectedRows != 0) {
      return res.send({
        code: 200,
        msg: "修改成功",
      });
    } else {
      return res.send({
        code: 0,
        msg: "修改失败",
      });
    }
  } else {
    const sql = `INSERT INTO sign(user_name,gender,phone,base_name,user_code,create_time) VALUES(?,?,?,?,?,?)`;
    const sqlRes = await global.query(sql, [user_name, gender, phone, base_name, user_code, create_time])
    if (sqlRes.affectedRows != 0) {
      return res.send({
        code: 200,
        msg: "添加成功",
      });
    } else {
      return res.send({
        code: 0,
        msg: "添加失败",
      });
    }
  }
};
